package com.example.meetdroid;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.meetdroid.Interfaces.IClientEvents;
import com.example.meetdroid.main.Client;
import com.example.meetdroid.main.Globals;
import com.example.meetdroid.main.User;
import com.example.meetdroid.main.Client.Message;
import com.example.meetdroid.main.UserRequester;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

public class LoginActivty extends Activity implements IClientEvents {

	ImageView cImageStatus;
	Button cBtnLogin;
	EditText cTxtUserName;
	EditText cTxtPassword;
	private CheckBox cCBSaveData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_activty);
        this.InitGlobals();
		cTxtUserName = (EditText) findViewById(R.id.txtUserName_Login);
		cTxtPassword = (EditText) findViewById(R.id.txtPassword);
		cBtnLogin = (Button) findViewById(R.id.mBtnLogin);
		this.cCBSaveData = (CheckBox) findViewById(R.id.login_activity_savedata); 
		if(cBtnLogin == null){
			Log.d("Meetup","BUTTON IS NULL!");
		}
		cBtnLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Globals.CurrentUser.setName(cTxtUserName.getText().toString());
				Globals.Client.LoginUser(cTxtUserName.getText().toString(), cTxtPassword.getText().toString());
			}
		});
	
		Globals.Client.addListener(this);
        Globals.Client.start();
        Globals.Client.initConnection();
        this.initLoginView();
    }

    private void initLoginView(){

    	if(DataStored()){
    	
	    	try {
				JSONObject obj = new JSONObject(this.LoadStoredData());
				cCBSaveData.setChecked(true);
				cTxtUserName.setText(obj.getString("UserName"));
				cTxtPassword.setText(obj.getString("Password"));
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}else{
    		cCBSaveData.setChecked(false);
    	}
    	
    	
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.login_activty, menu);
        return true;
    }
	private Boolean DataStored(){

		ContextWrapper cw = new ContextWrapper(getBaseContext());
		File directory = cw.getDir("media", Context.MODE_PRIVATE);
		File mediaDir = new File(directory+"\\LoginData.json");
		return mediaDir.exists();

	}
	private void InitGlobals(){
		try {
	        Globals.CurrentUser = new User();
	        Globals.FriendRequests = new ArrayList<UserRequester>();
	        Globals.FriendList = new ArrayList<User>();
	        Globals.Client = new Client();
	        
			
			Globals.AppPath = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0).applicationInfo.dataDir;
			Globals.AppContext = getApplicationContext();
		
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private Boolean StoreData(){
		
		ContextWrapper cw = new ContextWrapper(getBaseContext());
		File directory = cw.getDir("media", Context.MODE_PRIVATE);
		File f = new File(directory  + "\\LoginData.json");
		try {
			f.createNewFile();
		
		FileOutputStream fos = new FileOutputStream(f);
		byte[] b = this.LoginDataToJSON().getBytes();
		fos.write(b);
		fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e("MeetUp",e.getMessage());
			return false;
			
		}
		return true;
	}
	private String LoadStoredData(){
        String json = null;
        try {
        	ContextWrapper cw = new ContextWrapper(getBaseContext());
    		File directory = cw.getDir("media", Context.MODE_PRIVATE);
    		File f = new File(directory + "\\LoginData.json");
    		if(f.exists()){
				BufferedReader bufferedReader = new BufferedReader(new FileReader(f));
				String read;
				StringBuilder builder = new StringBuilder("");
				
				while((read = bufferedReader.readLine()) != null){
				     builder.append(read);
				   }
				Log.d("Output", builder.toString());
				bufferedReader.close();

				json = builder.toString();
    		}

        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
	}
	private String LoginDataToJSON(){

	    JSONObject jsonObject= new JSONObject();
	    try {
	        jsonObject.put("UserName",cTxtUserName.getText().toString() );
	        jsonObject.put("Password", cTxtPassword.getText().toString());
	        
	        return jsonObject.toString();
	    } catch (JSONException e) {
	        // TODO Auto-generated catch block
	        Log.e("Meetup",e.getMessage());
	        return "";
	    }

	}
	private void DeleteStoredData(){
		File mediaDir = new File("LoginData.json");
			if(mediaDir.exists()) mediaDir.delete();
					
	}
	@Override
	public void FriendRequestSended(String user) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void FriendRequestAccepted(User user) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void ConnectionEstablished() {
		runOnUiThread(new Runnable() {
	        public void run() {
	        	cBtnLogin.setEnabled(true);
	            cBtnLogin.setClickable(true);      
	        }
	    });
	}
	@Override
	public void UserLogedIn() {
		if(this.cCBSaveData.isChecked()){
			
			this.StoreData();
			
		}else{
			this.DeleteStoredData();
		}
		Intent intent = new Intent(this, MainSwipe.class);
		this.startActivity(intent);
		
	}
	@Override
	public void FriendReqeustRecived(UserRequester pRequester) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void FriendAdded(User friend) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void UserLoginFailed() {
		runOnUiThread(new Runnable() {
	        public void run() {
	        	Globals.ShowToast(Globals.AppContext, "Login fehlgeschlagen!");
	        }
	    });
		
		
	}
    
}

